package core;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import fileoperation.FileDeletion;
import repository.Repository;

public class JitInit {
	/**
	 * Init repository in your working area. The workTree should never be null.
	 * @param workTree
	 * @throws IOException
	 */
    public static void init(String workTree) throws IOException {
        Repository repo = new Repository(workTree);
        if(repo.exist()){
            if(repo.isDirectory()){
                Scanner sc = new Scanner(System.in);
                System.out.printf("Reinitialized existing Jit repository in %s"+File.separator+".jit\n", workTree);
                System.out.println("proceed and delete current repository press Y[or whatever], else n");
                String inp = sc.nextLine();
                if(inp.equalsIgnoreCase("n")) return;
                FileDeletion.deleteFile(Repository.getGitDir());
            }
            else if(repo.isFile()){
                throw new IOException(".jit is a file, please check");
            }
        }
        repo.createRepo();
        String regEmail = "^\\s*\\w+(?:\\.?[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        String path = Repository.getGitDir();
        System.out.println("Please enter user name: ");
        Scanner sc = new Scanner(System.in);
        String username = sc.nextLine();
        while(username.equals("")){
            System.out.println("username cannot be empty");
            username = sc.nextLine();
        }
        System.out.println("Please enter user email: ");
        String userEmail = sc.nextLine();
        while(!userEmail.matches(regEmail)){
            System.out.println("not a valid email, please check, example: 123a@163.com");
            userEmail = sc.nextLine();
        }
        FileWriter configWriter =  new FileWriter(path + File.separator + "config");
        BufferedWriter out = new BufferedWriter(configWriter);
        out.write("[user]"+"\n"+"\t"+"name = "+ username + "\n");
        out.write("\t"+"email = "+ userEmail+ "\n");
        out.close();
        configWriter.close();
        System.out.println("Jit repository has been initiated successfully.");
    }
}

